/* api */
import {getCustomer, getCustomerExeinsyn, getSynergiesByCustomer} from '@src/api/CustomerApi'
import {
  getTaskConfig,
  getTaskAutoDispatchApprove,
  taskAutoDispatch,
  getTaskAllotApprove,
  getTransferTaskAllotApprove,
  taskAllotExcutor,
  taskAllotTaskPoll,
  getTaskAllotTaskPoolApprove,
  getTaskType,
  taskReAllot,
  taskReAllotTaskPool,
  getTaskTypesMap,
  getTaskCalendarDispatch,
  getDefaultExecutor,
  checkNeedVipApprove
} from '@src/api/TaskApi'
import { getSettingCalendar, getStateColorMap } from '@src/api/SettingApi'
import { getConfig } from '@src/api/ProductV2Api'
/* computed */
import TaskAllotModalComputed from '@src/modules/task/components/TaskAllotModal/TaskAllotModalComputed'
/* decorators */
import Log from '@src/decorators/Log'
/* enum */
import TaskAllotTypeEnum from '@model/enum/TaskAllotTypeEnum'
import ComponentNameEnum from '@model/enum/ComponentNameEnum'
import StorageModuleEnum from '@model/enum/StorageModuleEnum'
import StorageKeyEnum from '@model/enum/StorageKeyEnum'
import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser/model/enum'
/* entity */
import LoginUser from '@model/entity/LoginUser/LoginUser'
import TaskConfig from '@model/config/TaskConfig'
import NewTaskConfig from '@model/config/NewTaskConfig'
import TaskApprove from '@model/entity/TaskApprove'
import TaskAllotUserInfo from '@model/entity/TaskAllotUserInfo'
import TaskType from '@model/entity/TaskType'
import TaskTypeSimple from '@model/entity/TaskTypeSimple'
import Tag from '@model/entity/Tag/Tag'
import { safeNewDate } from '@src/util/time';
/* interface */
import {
  AutoDispatchApproveParams,
  DepeMultiUserResult,
  AutoDispatchParams,
  AllotExcutorParams,
  AllotTaskPoolParams,
  User,
  ReAllotTaskPoolParams,
  TaskAllotResult
} from '@src/modules/task/components/TaskAllotModal/TaskAllotModalInterface'
/* model */
import { TaskAllotTypeModeEnum, ICreateEditTask } from '@src/modules/task/components/TaskAllotModal/TaskAllotModalModel'
import {
  TASK_NOT_AUTO_DISPATCH_RULE,
  TASK_NO_EXECUTOR_MESSAGE,
  TASK_NO_CALENDAR_START_TIME,
  TASK_NO_CALENDAR_END_TIME,
  TASK_ALLOT_NOT_STORAGE_RESULT,
  TASK_NO_REALLOT_REASON_MESSAGE,
  PLAN_START_TIME_NOT_LESS_THEN_NOW_MEESSAGE,
  PLAN_END_TIME_NOT_LESS_THEN_NOW_MEESSAGE,
  PLAN_END_TIME_NOT_LESS_THEN_PLAN_START_TIME_MEESSAGE,
  TASK_NO_REALLOR_CUSTOMREASON,
  TASK_REALLOT_NOT_SAME_USER_MESSAGE,
  TASK_SERVICE_DEPARTMENT_REQUIRES_MESSAGE
} from '@src/model/const/Alert'
import { getCustomerDetailResult } from '@model/param/out/Customer'
import { getTaskAllotApproveResult, getTaskAllotResult, getTaskAllotTaskPollApproveResult, getTaskAllotTaskPoolResult, getTaskConfigResult, getTaskTypeResult, getTaskTypesResult } from '@model/param/out/Task'
import { TaskPoolNotificationTypeEnum } from '@src/modules/task/components/TaskAllotModal/TaskAllotPool/TaskAllotPoolModel'
import { TaskAllotServiceProviderInfo } from '@src/modules/task/components/TaskAllotModal/TaskAllotServiceProvider/TaskAllotServiceProviderModel'
/* types */
import StateColorMap from '@model/types/StateColor'
import AutoDispatchListItem from '@model/types/AutoDispatchListItem'
/* util */
import LogUtil from '@src/util/log.ts'
import Platform from '@src/util/platform'
import PlatformUtil from '@src/platform'
import { openTabForTaskView } from '@src/util/business/openTab'
import { isArray } from '@src/util/type'
import { storageGet, storageSet } from '@src/util/storage.ts'
import { isEmpty } from '@src/util/lang/object'
import { addClass, removeClass } from '@src/util/dom';
import i18n from '@src/locales'
/* vue */
import { Emit } from 'vue-property-decorator'

import {enCodeAtText, getReceivers, atTextToHtml1} from '@src/util/atText'
import { cutAtTextContent } from 'pub-bbx-utils'
import { useTenantId, useRootUser } from '@hooks/useRootWindow';
import { t } from '@src/locales'

const PlanTimeClassName = 'body-for-plantime';
/* 加载的组件 */
const LoadComponentMap = {
  [TaskAllotTypeEnum.Person]: ComponentNameEnum.TaskAllotExcutor,
  [TaskAllotTypeEnum.Pool]: ComponentNameEnum.TaskAllotPool,
  [TaskAllotTypeEnum.Auto]: ComponentNameEnum.TaskAllotAuto,
  [TaskAllotTypeEnum.ServiceProvider]: ComponentNameEnum.TaskAllotServiceProvider,

}

enum TaskAllotModalEmitEventEnum {
  Success = 'success',
  UpdateTask = 'updateTask',
  UpdateRecords = 'updateRecords',
}

class TaskAllotModalMethods extends TaskAllotModalComputed {

  /** 
   * @description 派单成功
   * 默认实现。跳转到工单详情页面 如果有需要可以自定义
  */
  @Emit(TaskAllotModalEmitEventEnum.Success)
  public async allotSuccess(): Promise<void> {
    
    LogUtil.succ(LogUtil.Start, this.allotSuccess.name)
    
    // 保存派单结果到缓存
    await this.saveAllotResultToStorage()

    // 如果当前页面是指派工单列表页，不做下列操作
    if(this.source === 'allotList') return
    
    // @ts-ignore
    let id = window?.frameElement?.dataset?.id
    let fromId = window?.frameElement?.getAttribute('fromid');
    // 刷新指派列表
    if(this.isCopyTask) {
      PlatformUtil.refreshTab('frame_tab_M_TASK_LIST');
    } else {
      PlatformUtil.refreshTab(fromId);
    }
    // 关闭当前tab
    PlatformUtil.closeTab(id)
    // 打开新tab
    openTabForTaskView(this.task.id)
  }

  /** 
   * @description 更新工单信息
  */
  @Emit(TaskAllotModalEmitEventEnum.UpdateTask)
  public updateTaskHandler(task: any) {
    LogUtil.succ(LogUtil.Start, this.updateTaskHandler.name)
    return task
  }

  /** 
   * @description 更新工单动态
  */
  @Emit(TaskAllotModalEmitEventEnum.UpdateRecords)
  public updateTaskRecordsHandler() {
    LogUtil.succ(LogUtil.Start, this.updateTaskRecordsHandler.name)
  }

  /** 
   * @description 构建自动派单审批参数
  */
  public buildAutoDispatchApproveParams(): AutoDispatchApproveParams {
    let params: AutoDispatchApproveParams = {
      taskId: this?.task?.id || ''
    }

    // 有使用匹配的规则并且使用预估结果
    if (this.matchRule && this.isUsedResult) {
      params.estimatedMatches = this.getParamsMatchRule()
    }

    // 存在协同人信息
    if (this.synergyUserList.length > 0) {
      params.synergies = this.getParamsSynergies()
    }

    return params
  }

  /** 
   * @description 构建派单到负责人参数
  */
  public buildAllotExcutorParams(): AllotExcutorParams {
    let params: AllotExcutorParams = {
      taskId: this.task?.id || '',
      executorId: this.executorUser?.userId || ''
    }

    // 存在协同人信息
    if (this.synergyUserList.length > 0) {
      params.synergies = this.getParamsSynergies()
    }

    // 存在计划开始时间和计划完成时间
    if (this.allotTypeMode === TaskAllotTypeModeEnum.Calendar) {
      params.planStartTime = safeNewDate(this.calendarStartTime)
      params.planEndTime = safeNewDate(this.calendarEndTime)
    }

    return params
  }

    /** 
   * @description 构建派单到服务商参数
  */
  public buildAllotServiceProviderParams() {
      let params = {
        taskId: this.task?.id || '',
        executorId: this.serviceProvider.map(item =>item.userId).join()|| '',
        serviceProviderName:this.serviceProvider[0].serviceProviderName,
        serviceProviderId:this.serviceProvider[0].serviceProviderId
      }
      // 存在协同人信息
      if (this.synergyUserList.length > 0) {
        // @ts-ignore
        params.synergies = this.getParamsSynergies()
      }
      return params
    }
  /** 
   * @description 构建派单到工单池参数
  */
  public buildAllotTaskPoolParams(): AllotTaskPoolParams {
    let taskPoolData: { checked: TaskPoolNotificationTypeEnum[], users: LoginUser[] } = (
      // @ts-ignore
      this.$refs?.TaskAllotPoolComponent?.outsideBuildData()
      || { checked: [], users: [] }
    )

    let params: AllotTaskPoolParams = {
      taskId: this.task?.id || '',
      noticeCusTag: taskPoolData.checked.includes(TaskPoolNotificationTypeEnum.SendToTeamUser),
      authTaskPoolUser: taskPoolData.checked.includes(TaskPoolNotificationTypeEnum.SendToAuthUser),
      otherNotifier: (
        taskPoolData.checked.includes(TaskPoolNotificationTypeEnum.SendToOtherUser)
          ? taskPoolData.users
          : []
      )
    }

    // 存在协同人信息
    if (this.synergyUserList.length > 0) {
      params.synergies = this.getParamsSynergies()
    }

    return params
  }

  /** 
   * @description 构建自动派单参数
  */
  public buildAutoDispatchParams(): AutoDispatchParams {
    let params: AutoDispatchParams = {
      taskId: this?.task?.id || '',
      executorId: 'auto_dispatch'
    }

    // 有使用匹配的规则
    if (this.matchRule) {
      params.autoDispatchInfo = this.getParamsMatchRule()
    }

    // 存在协同人信息
    if (this.synergyUserList.length > 0) {
      params.synergies = this.getParamsSynergies()
    }

    return params
  }

  /** 
   * @description 构建转派到负责人参数
  */
  public buildReAllotParams(): AllotExcutorParams {
    let reAllotParams = this.buildAllotExcutorParams()
    reAllotParams.reason = this.reason
    reAllotParams.customReason = this.customReason

    return reAllotParams
  }

  /** 
   * @description 构建转派到工单池参数
  */
  public buildReAllotTaskPoolParams(): ReAllotTaskPoolParams {
    let reAllotTaskPoolParams: any = this.buildAllotExcutorParams()
    reAllotTaskPoolParams.reason = this.reason
    reAllotTaskPoolParams.executorId = 'task_pool'
    reAllotTaskPoolParams.toPool = true
    reAllotTaskPoolParams.state = this.task?.state

    return reAllotTaskPoolParams
  }

  /** 
   * @description 选择协同人
  */
  public chooseSynergyUser(): void {
    let options = {
      title: i18n.t('common.placeholder.selectSomething', {0: i18n.t('task.synergies')}),
      seeAllOrg: true,
      selectedUsers: this.synergyUserList,
      max: this.maxSynergyUserCount,
      showUserState: true,
      mode: BaseSelectUserModeEnum.Filter
    };
    
    
    // @ts-ignore
    this.$fast.select.multi.user(options)
      .then((result: DepeMultiUserResult) => {
        let isSuccess = result.status == 0
        if (!isSuccess) return

        // 协同人赋值
        this.synergyUserList = result?.data?.users || []
      })
      .catch((err: any) => {
        console.error(err)
      })
  }

  /** 
   * @description 关闭弹窗
  */
  public close(): void {
    this.showTaskAllotModal = false
  }

  /**
   * @description 清空派单结果
  */
  public clearTaskAllotResult(event: MouseEvent): void {
    // @ts-ignore 取消按钮的焦点
    event?.target?.parentNode?.blur()
    // 清空上次派单结果
    const allotType = TaskAllotTypeEnum.Person
    this.handlerAllotTypeChange(allotType)
    this.executorUser = null
    this.synergyUserList = []
    this.calendarStartTime = ''
    this.calendarEndTime = ''
    // 隐藏清空派单结果按钮
    this.showClearTaskAllotResultButton = false
  }

  /**
   * @description 清空人员卡片
   */
  public clearUserCardSynergyChecked(user: LoginUser) {
    this.UserCardComponentWithTaskAllotExecutorMap?.clearSynergyChecked(user)
    this.UserCardComponentWithTaskAllotPool?.clearSynergyChecked(user)
  }

  /** 
   * @description 删除协同人
  */
  public deleteSynergyUser(user: LoginUser) {
    this.synergyUserList = (
      this.synergyUserList
        .filter((synergyUser: LoginUser) => {
          return synergyUser.userId !== user.userId
        })
    )
  }

  /** 
   * @description 获取属性列表
  */
  public getAttributes() {
    const classNames = ['task-allot-modal', this.isReAllot && 'task-reallot-modal']

    return {
      class: classNames,
      props: {
        title: i18n.t('task.components.taskAllotModal.allotTask'),
        size: 'larger',
        className: classNames
      },
      on: {
        'update:show': (val: any) => {
          this.showTaskAllotModal = val
          if (!val) {
            if (this.isCalendar) {
              removeClass(document.body, PlanTimeClassName);
            }
          }
        },
      },
      directives: [
        {
          name: 'loading',
          value: this.pending,
          modifiers: {
            fullscreen: true,
            lock: true,
          }
        }
      ]
    }
  }

  /** 
   * @description 获取匹配规则参数
  */
  public getParamsMatchRule() {
    let { finalExecutorId, finalExecutorName, finalRuleId, finalRuleName } = this.matchRule || {}

    return {
      finalExecutorId: finalExecutorId || '',
      finalExecutorName: finalExecutorName || '',
      finalRuleId: finalRuleId || '',
      finalRuleName: finalRuleName || '',
    }
  }

  /** 
   * @description 获取协同人信息参数
  */
  public getParamsSynergies(): User[] {
    return (
      this.synergyUserList.map((user: LoginUser) => {
        return {
          displayName: user.displayName,
          head: user.head,
          userId: user.userId,
          staffId: user.staffId,
        }
      })
    )
  }

  /**
   * @description 从缓存获取数据
  */
  public async getDataToStorage(key: string, data: any) {
    return await storageGet(key, data, StorageModuleEnum.Task, true, false)
  }

  /**
   * @description 查询所有的工单类型列表
   */
  public fetchTaskTypesMap() {
    // 如果工单类型列表数据已存在则不查询
    if (this.taskTypes.length > 0) return

    LogUtil.succ(LogUtil.Start, `TaskAllotModalMethods -> ${this.fetchTaskTypesMap.name}`)

    return (
      getTaskTypesMap().then((data: getTaskTypesResult) => {
        let isSuccess = data.success
        if (!isSuccess) return

        const taskTypeSimpleList: TaskTypeSimple[] = data?.result || []
        this.taskTypes = taskTypeSimpleList.map(taskTypeSimple => TaskTypeSimple.toTaskType(taskTypeSimple))
        // key : 工单类型id(string) -> value: TaskType
        this.taskTypesMap = (
          this.taskTypes
            .reduce((acc: { [x: string]: TaskType }, currentTaskType: TaskType) => {
              acc[currentTaskType.templateId] = currentTaskType
              return acc
            }, {})
        )

      }).catch(err => {
        console.error(err)
      })
    )
  }

  /**
   * @description 获取客户信息
  */
  public fetchCustomer() {
    let id = this.customerId
    if (!id) {
      return console.warn('Caused: TaskAllotModal fetchCustomer not have customerId')
    }

    LogUtil.succ(LogUtil.Start, `TaskAllotModalMethods -> ${this.fetchCustomer.name}`)

    return (
      getCustomer(id).then((result: getCustomerDetailResult) => {
        let isSuccess = result.status == 0
        if (!isSuccess) return

        LogUtil.succ(LogUtil.End, `TaskAllotModalMethods -> ${this.fetchCustomer.name}`)

        this.customer = Object.freeze(result.data || {})

        // 查询用户数据
        this.TaskAllotExcutorComponent?.outsideFetchUsers()

      }).catch(err => {
        console.error(err)
      })
    )
  }

  /** 
   * @description 查询工单配置
  */
  public fetchTaskConfig() {
    return (
      getTaskConfig()
        .then((result: getTaskConfigResult) => {
          this.taskConfig = result.taskConfig || new TaskConfig()
          this.newTaskConfig = result?.newTaskConfig || new NewTaskConfig()
        })
        .catch(err => {
          console.warn(err)
        })
    )
  }

  /** 
   * @description 查询工单类型配置
  */
  public fetchTaskType() {
    let params = { id: this.task.templateId }
    // 查询工单类型数据
    return (
      getTaskType(params)
        .then((result: getTaskTypeResult) => {
          let isSuccess = result.succ
          if (!isSuccess) return

          this.taskType = result.data || null

        })
        .catch(err => {
          console.error(err)
        })
    )
  }
  /**
   * @description 根据客户id获取客户协同人
   */
  public async fetchSynergiesByCustomer() {
    if (!this.customerId) return console.warn('fetchSynergiesByCustomer paramer not have customerId')
    try {
      const { data } = await getConfig({configCode: ['SYNERGIER_AUTO_IMPORT_TASK_EVENT']});
      if(!data?.[0]?.isOpen) return; // 不允许自动将客户协同人带入工单或事件协同人
      const { result } = await getSynergiesByCustomer(this.customerId);
      result?.forEach((item: any) => {
        let isRepeatUser = this.synergyUserList.some(user => user.userId == item.userId)
        !isRepeatUser && this.synergyUserList.push(item);
      })
    }catch (e) {
      console.error(e)
    }
  }
  /** 
   * @description 根据客户id获取客户信息和客户负责人信息和开关 
  */
  public fetchSynergyUserWithCustomerManager() {
    let customerId = this.customerId
    if (!customerId) return console.warn('fetchExeinsynWithCustomerManager paramer not have customerId')

    return (
      getCustomerExeinsyn({ id: customerId }).then(result => {
        let exeInSynOfTaskOrEvent = result?.data?.exeInSynOfTaskOrEvent;
        // 允许自动将客户负责人带入工单或事件协同人
        if (exeInSynOfTaskOrEvent) {
          // 判断用户id是否存在 且 目前的协同人列表中是否已存在
          let userId: string = result?.data?.userId
          let isHaveUserId = Boolean(userId)
          let isRepeatUser = isHaveUserId ? this.synergyUserList.some(user => user.userId == userId) : false
          isHaveUserId && !isRepeatUser && this.synergyUserList.push(result.data)
        }
      })
    )

  }

  /** 初始化工作状态的颜色 */
  public fetchStateColor(): Promise<any> {
    return (
      getStateColorMap()
        .then((res: StateColorMap) => {
          this.stateColorMap = res || {}
        })
        .catch(err => console.error(err))
    )
  }

  /* 派单审批 */
  public fetchApproveWithTaskAllot(params: AllotExcutorParams, isReAllot: Boolean = false): Promise<any | null> {
    let fetchAllotApproveAction = isReAllot ? getTransferTaskAllotApprove : getTaskAllotApprove;
    return (
      fetchAllotApproveAction(params)
      .then(async (result: getTaskAllotApproveResult) => {
        let isSuccess = result.succ
        // TODO 需要审批判断改成errorCode
        console.log(!isSuccess, Number(result.errorCode), Number(result.errorCode) !== 10003, !isSuccess && Number(result.errorCode) !== 10003, 'errorCode')
        if (!isSuccess && Number(result.errorCode) !== 10003) {
          let confirm = await Platform.alert(result.message)
          if (confirm) window.location.reload()
          return false
        } else if(!isSuccess && Number(result.errorCode) === 0){
          let confirm = await Platform.alert(result.message)
          if (confirm) return false
        }else {
          let isNeedApprove = !isSuccess && Number(result.errorCode) === 10003
          return {
            isNeedApprove,
            data: result.data || {}
          }
        }
      }).catch((err) => {
          this.pending = false
          console.error(err)
          return null
        })
    )
  }

  /* 指派到工单池审批 */
  public fetchTaskAllotTaskPoolApprove(params: AllotTaskPoolParams): Promise<TaskApprove | any | null> {
    return (
      getTaskAllotTaskPoolApprove(params)
        .then(async (result: getTaskAllotTaskPollApproveResult) => {
          let isSuccess = result.succ
          // TODO 需要审批判断改成errorCode
          if (!isSuccess && Number(result.errorCode) !== 10003) {
            let confirm = await Platform.alert(result.message)
            if (confirm) window.location.reload()
            return false
          } else {
            let isNeedApprove = !isSuccess && Number(result.errorCode) === 10003

            return {
              isNeedApprove,
              data: result.data || {}
            }
          }
        }).catch((err) => {
          this.pending = false
          console.error(err)
          return null
        })
    )
  }

  /* 自动派单审批状态 */
  public fetchApproveWithAutoDispatch(params: AutoDispatchApproveParams): Promise<{ isNeedApprove: boolean, data: TaskApprove } | null> {
    return (
      getTaskAutoDispatchApprove(params)
        .then((result) => {
          let isSuccess = result.succ
          // TODO 需要审批判断改成errorCode
          let isNeedApprove = !isSuccess && Number(result.errorCode) === 10003

          return {
            isNeedApprove,
            data: result.data || {}
          }

        }).catch((err) => {
          this.pending = false
          console.error(err)
          return null
        })
    )
  }

  /* 派单到负责人提交 */
  public fetchExcutorSubmit(params: AllotExcutorParams, allotTypeMode: TaskAllotTypeModeEnum) {
    // 增加保存并派单参数
    if (this.createEditTask?.createAndAllot) {
      params.createAndAllot = this.createEditTask.createAndAllot
    }
    return (
      taskAllotExcutor(params)
        .then((data: getTaskAllotResult) => {
          let isSuccess = data.success
          if (!isSuccess) {
            return Platform.alert(data.message)
          }

          data?.result?.stateDisplayName
            && (
              Platform.notification({
                title: this.$t(`common.base.${data?.result?.stateDisplayName}`),
                type: 'success',
              })
            )
          const type = allotTypeMode === TaskAllotTypeModeEnum.ServiceProvider ? 'ALLOT_TO_SERVICE_PROVIDER' : 'ALLOT_TO_EXECUTOR';
          // @ts-ignore
          this.$track.clickStat(this.$track.formatParams(type, null ,'SUBMIT_ALLOT'));
          this.allotSuccess()
        })
        .catch((err: any) => {
          console.error(err)
        })
        .finally(() => {
          this.pending = false
        })
    )
  }

  /* 派单到工单池提交 */
  public fetchTaskPoolSubmit(params: AllotTaskPoolParams) {
    return (
      taskAllotTaskPoll(params)
        .then((data: getTaskAllotTaskPoolResult) => {
          let isSuccess = data.success
          if (!isSuccess) {
            return Platform.alert(data.message)
          }

          data?.result?.stateDisplayName
            && (
              Platform.notification({
                title: data?.result?.stateDisplayName || '',
                type: 'success',
              })
            )
          
          const { checked } = this.$refs?.TaskAllotPoolComponent?.outsideBuildData() || { checked: [] };
          const checkMap = {
            sendToTeamUser: '通知服务团队人员',
            sendToAuthUser: '通知有权限接单用户',
            sendToOtherUser: '其他需要通知的人'
          }
          // @ts-ignore
          const allotPoolNotice = checked.map(item => checkMap[item]).join(',');
          // @ts-ignore
          this.$track.clickStat(this.$track.formatParams('ALLOT_TO_POOL', allotPoolNotice ,'SUBMIT_ALLOT'));
          
          this.allotSuccess()
        })
        .catch((err: any) => {
          console.error(err)
        })
        .finally(() => {
          this.pending = false
        })
    )
  }

  /* 自动派单 */
  public fetchAutoDispatchSubmit(params: AutoDispatchParams) {
    return (
      taskAutoDispatch(params)
        .then((data: any) => {
          let isSuccess = data.success
          if (!isSuccess) {
            return Platform.alert(data.message)
          }

          data?.result?.stateDisplayName
            && (
              Platform.notification({
                title: data?.result?.stateDisplayName || '',
                type: 'success',
              })
            )
          // @ts-ignore
          this.$track.clickStat(this.$track.formatParams('ALLOT_AUTO', null ,'SUBMIT_ALLOT'));
          this.allotSuccess()
        })
        .catch((err: any) => {
          console.error(err)
        })
        .finally(() => {
          this.pending = false
        })
    )
  }

  /* 转派工单到负责人提交 */
  public fetchReAllotSubmit(params: AllotExcutorParams) {
    let receivers = ''
    let query = ''
    let remark = params.reason||''
    let sendUser:any = useRootUser().value
    if(params.reason){
      remark = enCodeAtText(params.reason, this.atUsers);
      receivers = getReceivers(params.reason, this.atUsers)
      let queryData:any = {
        receivers,
        tenantId: useTenantId().value,
        content: cutAtTextContent(params.reason),
        sendUserName: sendUser?.displayName,
        bizId: params.taskId,
        bizNo: this.task.taskNo,
      };
      query = '?';
      for (let i in queryData) {
        query += `&${i}=${queryData[i]}`;
      }
    }
    params.reason = remark
    return (
      taskReAllot(params,query)
      .then((data: getTaskAllotResult) => {
        let isSuccess = data.success
        if (!isSuccess) {
          return Platform.alert(data.message)
        }
        
        this.allotSuccess()
      })
      .catch((err: any) => {
        console.error(err)
      })
      .finally(() => {
        this.pending = false
      })
    )
  }

  /* 转派工单到工单池提交 */
  public fetchReAllotTaskPoolSubmit(params: ReAllotTaskPoolParams) {
    return (
      taskReAllotTaskPool(params)
        .then((data: getTaskAllotResult) => {
          let isSuccess = data.success
          if (!isSuccess) {
            return Platform.alert(data.message)
          }

          data?.result?.stateDisplayName
            && (
              Platform.notification({
                title: data?.result?.stateDisplayName || '',
                type: 'success',
              })
            )

          this.allotSuccess()
        })
        .catch((err: any) => {
          console.error(err)
        })
        .finally(() => {
          this.pending = false
        })
    )
  }

  /** 
   * @description 派单方式变化
  */
  public handlerAllotTypeChange(type: TaskAllotTypeEnum, defaultDispatch?: boolean) {
    this.allotType = type
    // 如果是服务商派单或者派单到负责人，则更改派单模式
    if (type === TaskAllotTypeEnum.ServiceProvider) {
      this.allotTypeMode = TaskAllotTypeModeEnum.ServiceProvider
    } else if(type === TaskAllotTypeEnum.Person){
      // 指派工单负责人列表清空
      this.TaskAllotExcutorComponent?.removeTaskAllotUserList()
      !defaultDispatch ? this.initialize() : ''
      this.allotTypeMode = TaskAllotTypeModeEnum.List
    }
    this.loadedComponents.length = 0 // 清除已加载组件，防止重复渲染
    this.loadedComponents.push(LoadComponentMap[type])
    this.fetchTaskTypesMap()
  }

  /** 
 * @description 派单方式模式变化
*/
  public handlerAllotTypeModeChange(type: TaskAllotTypeModeEnum) {
    const typeMap = {
      list: '列表',
      map: '地图',
      calendar: '日历',
      serviceProvider: '服务商',
    }
    // @ts-ignore
    this.$track.clickStat(this.$track.formatParams('TASK_ALLOT_TYPE_MODE_SWITCH', typeMap[type]));

    this.allotTypeMode = type
    this.fetchTaskTypesMap()
  }

  /** 
   * @description 初始化
  */
  public async initialize() {
    try {

      await this.fetchStateColor()
      // 异步获取客户信息
      await this.fetchCustomer()
      // 非转派时获取客户负责人带入协同人
      !this.isReAllot && await this.fetchSynergyUserWithCustomerManager()
      // 获取客户协同人带入协同人（不需要判断转派与否）
      await this.fetchSynergiesByCustomer();
      // 转派时将转派人设置为协同人
      this.isReAllot && this.isShowAssignorToSynergyUser && this.fetchSynergyUserWithReAllot()

    } catch (error) {
      this.toggleTaskAllotExecutorComponentPending()
      LogUtil.error(error, this.initialize.name)
    } finally {
      this.pending = false
    }
  }

  /** 
   * @description 转派匹配负责人显示
  */
  public matchExcutorWithReAllot(): void {
    if (!this.isReAllot) return

    let executor: LoginUser = this.task?.executor
    executor ? executor.selfSelected = true : null
    this.executorUser = executor || null
  }

  /** 
   * @deprecated
   * @description 工单池通知方式变动
  */
  public onTaskNotificationCheckedChanged(value: TaskPoolNotificationTypeEnum[]): void {
    this.taskPoolNotificationCheckd = value
  }

  /** 
   * @description 是否使用自动匹配预估结果
  */
  public onIsUsedResultChanged(used: boolean) {
    this.isUsedResult = used
  }

  /** 
   * @deprecated
   * @description 工单池通知人员信息变动
  */
  public onTaskNotificationUsersChanged(value: LoginUser[]): void {
    LogUtil.succ(LogUtil.Start, this.onTaskNotificationUsersChanged.name)
    this.taskPoolNotificationUsers = value
  }

  /** 
   * @description 设置负责人信息
   * -- 支持外部调用的
  */
  public outsideSetExcutorUser(user: LoginUser | TaskAllotUserInfo | null) {
    LogUtil.succ(LogUtil.Start, this.outsideSetExcutorUser.name)
    this.setExecutorUser(user)
  }

  /** 
   * @description 设置匹配的规则
   * -- 支持外部调用的
  */
  public outsideSetMatchRule(rule: AutoDispatchListItem | null) {
    LogUtil.succ(LogUtil.Start, this.outsideSetMatchRule.name)
    this.matchRule = rule
  }

  /** 
   * @description 设置工单信息
   * -- 支持外部调用的
  */
  public outsideSetTask(task: any) {
    LogUtil.succ(LogUtil.Start, this.outsideSetTask.name)
    this.updateTaskHandler(task)
    this.updateTaskRecordsHandler()
  }

  /** 
   * @description 删除协同人信息
   * -- 支持外部调用的
  */
  public outsideDeleteSynergyUser(user: LoginUser) {
    LogUtil.succ(LogUtil.Start, this.outsideDeleteSynergyUser.name)
    this.deleteSynergyUser(user)
    this.clearUserCardSynergyChecked(user)
  }

  /** 
   * @description 删除服务商信息
   * -- 支持外部调用的
  */
  public outsideDeleteServiceProvider(user: TaskAllotServiceProviderInfo) {
    // 过滤掉当前选中的服务商
    this.serviceProvider = this.serviceProvider.filter((item:TaskAllotServiceProviderInfo) => item.userId !== user.userId)
  }

  /** 
   * @description 设置协同人列表
   * -- 支持外部调用的
  */
  public outsideSetSynergyUsers(users: LoginUser[]) {
    LogUtil.succ(LogUtil.Start, this.outsideSetSynergyUsers.name)
    this.setSynergyUsers(users)
  }

  /** 
   * @description 设置开始时间
   * -- 支持外部调用的
  */
  public outsideSetStartTime(time: string) {
    LogUtil.succ(LogUtil.Start, this.outsideSetStartTime.name)
    this.setStartTime(time)
  }

  /** 
   * @description 设置结束时间
   * -- 支持外部调用的
  */
  public outsideSetEndTime(time: string) {
    LogUtil.succ(LogUtil.Start, this.outsideSetEndTime.name)
    this.setEndTime(time)
  }

  /**
   * @description 设置客户团队信息列表
   * -- 支持外部调用的
   */
  public outsideSetCustomerTags(tags: Tag[]) {
    LogUtil.succ(LogUtil.Start, this.outsideSetCustomerTags.name)
    this.customerTags = tags
  }

  /**
   * @description 设置转派说明信息
   * -- 支持外部调用的
   */
  public outsideSetReason(value: string) {
    LogUtil.succ(LogUtil.Start, this.outsideSetReason.name)
    this.reason = value
  }

  /**
   * @description 设置转派At人员
   * -- 支持外部调用的
   */
   public outsideSetAtUsers(value: []) {
    this.atUsers = value
  }
  /**
   * @description 工单转派
   */
  public outsideSetCustomReason(value: string) {
    this.customReason = value
  }

  /** 
   * @description 显示弹窗
   * --支持外部调用的
  */
  public async outsideShow(createEditTask:ICreateEditTask) {
    this.createEditTask = createEditTask || {}
    LogUtil.succ(LogUtil.Start, this.outsideShow.name)
    // 等待状态
    this.pending = true
    this.toggleTaskAllotExecutorComponentPending(false)
    // 初始化派单类型 在 getDefaultDispatch 中修改了allotType的值
    this.allotType = TaskAllotTypeEnum.Person
    // 初始化视图模式
    this.allotTypeMode = TaskAllotTypeModeEnum.List
    // 匹配负责人显示
    this.matchExcutorWithReAllot()
    // 初始化协同人显示
    this.synergyUserList = isArray(this.task?.synergies) ? this.task.synergies.slice() : []
    // 获取工单配置
    await this.fetchTaskConfig()
    // 获取是否有工单编辑权限
    this.getUserTaskCalendarDispatch()
    // 获取是否开通了日历派单
    await this.getSetCalendar()
    // 获取默认派单设置
    !this.isReAllot && this.getDefaultDispatch()
    // 初始化
    this.initialize()
    // 显示
    this.show()
  }
  /** 
   * @description 设为负责人
  */
  public setExecutorUser(user: LoginUser | TaskAllotUserInfo | null) {
    LogUtil.succ(LogUtil.Start, this.setExecutorUser.name)
    this.executorUser = user
  }

  /** 
   * @description 设为服务商
  */
  public setServiceProvider(list: TaskAllotServiceProviderInfo[]): void{
    this.serviceProvider = list
  }


  
  /** 
   * @description 设为协同人
  */
  public setSynergyUser(user: LoginUser) {
    LogUtil.succ(LogUtil.Start, this.setSynergyUser.name)
    // 判断是否已存在该用户
    const IsNotRepeat = this.synergyUserList.every(synergyUser => synergyUser.userId !== user.userId)
    IsNotRepeat && this.synergyUserList.push(user)
  }

  /** 
   * @description 设置协同人列表数据
  */
  public setSynergyUsers(users: LoginUser[]) {
    this.synergyUserList = users
  }

  /** 
   * @description 设置计划开始时间数据
  */
  public setStartTime(time: string) {
    this.calendarStartTime = time
  }

  /** 
   * @description 设置计划开始时间数据
  */
  public setEndTime(time: string) {
    this.calendarEndTime = time
  }

  /** 
   * @description 显示弹窗
  */
  public show() {
    // 显示弹窗
    this.showTaskAllotModal = true
    if (this.isCalendar) {
      addClass(document.body, PlanTimeClassName);
    }
  }

  /** 
   * @description 显示审批弹窗
  */
  public showApproveDialog(data: TaskApprove, customReason: String = '') {

    // @ts-ignore
    this.$refs?.ApproveDialog?.openDialog(data, customReason ? { customReason } : '')
  }

  /**
   * @description 保存数据到缓存
  */
  public async saveDataToStorage(key: string, data: any): Promise<void> {
    await storageSet(key, data, StorageModuleEnum.Task)
  }

  /**
   * @description 保存派单结果到缓存
  */
  public async saveAllotResultToStorage(): Promise<void> {
    LogUtil.succ(LogUtil.Start, this.saveAllotResultToStorage.name)
    // 工单派单结果
    const taskAllotResult: TaskAllotResult = {
      // 派单方式
      allotType: this.allotType,
      // 负责人
      executorUser: this.executorUser as LoginUser,
      // 协同人列表
      synergyUserList: this.synergyUserList,
      // 计划开始时间
      calendarStartTime: this.calendarStartTime,
      // 计划完成时间
      calendarEndTime: this.calendarEndTime
    }
    // 保存数据
    await this.saveDataToStorage(StorageKeyEnum.TaskAllotResult, taskAllotResult)
  }

  /** 
   * @description 提交
  */
  public submit() {
    this.pending = true
    // 转派 提交
    if (this.isReAllot) {
      return this.submitWithReAllot()
    }

    // 按工单负责人
    if (this.allotType === TaskAllotTypeEnum.Person) {
      return this.submitWithExcutor()
    }

    // 派单到工单池
    if (this.allotType === TaskAllotTypeEnum.Pool) {
      return this.submitWithTaskPool()
    }

    // 自动分配
    if (this.allotType === TaskAllotTypeEnum.Auto) {
      return this.submitWithAutoDispatch()
    }
    
    // 派单到服务商
    if (this.allotType === TaskAllotTypeEnum.ServiceProvider) {
      return this.submitWithServiceProvider()
    }
  }
  // 派单到服务商
  private async submitWithServiceProvider() {
    try {
      // 验证服务商是否存在
      
      if (!this.serviceProvider.length) {
        this.pending = false
        return Platform.alert(TASK_SERVICE_DEPARTMENT_REQUIRES_MESSAGE)
      }
      // 验证审批
      const allotServiceProviderParams = this.buildAllotServiceProviderParams()


      // 先判断是否需要高级审批
      let isNeedVipApprove = false
      let approveParams = {
        taskId: this.task?.id || '',
        action: this.isReAllot ? 'reAllot' : 'allot',
        allotInfo: allotServiceProviderParams,
      }
      await checkNeedVipApprove(approveParams).then((res: any) => {
        if (res?.success) {
          isNeedVipApprove = res?.result?.needVipApprove ?? false
          this.pending = false
          if (isNeedVipApprove) {
            return this.showApproveDialog(res?.result)
          }
        }
      })

      if (isNeedVipApprove) { return }

      let approve: any | null = await this.fetchApproveWithTaskAllot(allotServiceProviderParams)
      if (!approve) return
      let isNeedApprove = approve.isNeedApprove === true
      // 有审批
      if (isNeedApprove) {
        this.pending = false
        return this.showApproveDialog(approve.data)
      }
      
      // 派单提交
      this.fetchExcutorSubmit(allotServiceProviderParams, this.allotTypeMode)

    } catch (error) {
      this.pending = false
      console.warn('TaskAllotModalMethods -> submitWithExcutor -> error', error)
    }
  }
  /** 
   * @description 转派提交
  */
  public async submitWithReAllot() {
    try {
      // 效验
      if (this.notNull && !this.customReason) {
        this.pending = false
        return Platform.alert(TASK_NO_REALLOR_CUSTOMREASON)
      }

      if (this.reallotRemarkNotNull && !this.reason) {
        this.pending = false
        return Platform.alert(TASK_NO_REALLOT_REASON_MESSAGE)
      }

      // 按工单负责人
      if (this.allotType === TaskAllotTypeEnum.Person) {
        return this.submitReAllotWithExecutor()
      }

      // 派单到工单池
      if (this.allotType === TaskAllotTypeEnum.Pool) {
        return this.submitWithTaskPool()
      }

      // 派单到服务商
      if (this.allotType === TaskAllotTypeEnum.ServiceProvider) {
        return this.submitReAllotWithServiceProvider()
      }

    } catch (err) {
      this.pending = false
      console.error(err)
    }
  }

  // 转派提交到服务商
  public async submitReAllotWithServiceProvider() {
    // 验证负责人是否存在
    let executor = this.serviceProvider[0]?.userId
    if (!executor) {
      this.pending = false
      Platform.notification({
        title: TASK_SERVICE_DEPARTMENT_REQUIRES_MESSAGE,
        type: 'error',
      });
      return
    }
    // 验证服务商是否相同
    if (executor === this.task?.executor.userId) {
      this.pending = false
      Platform.notification({
        title: TASK_REALLOT_NOT_SAME_USER_MESSAGE,
        type: 'error',
      });
      return
    }

    // 验证审批
    const allotExecutorParams = this.buildAllotServiceProviderParams()
    let reAllotParams = this.buildAllotServiceProviderParams()
    // @ts-ignore
    reAllotParams.reason = this.reason
    // @ts-ignore
    reAllotParams.customReason = this.customReason

    // 先判断是否需要高级审批
    let isNeedVipApprove = false
    let approveParams = {
      taskId: this.task?.id || '',
      action: this.isReAllot ? 'reAllot' : 'allot',
      allotInfo: reAllotParams
    }
    await checkNeedVipApprove(approveParams).then((res: any) => {
      if (res?.success) {
        isNeedVipApprove = res?.result?.needVipApprove ?? false
        this.pending = false
        if (isNeedVipApprove) {
          return this.showApproveDialog(res?.result)
        }
      }
    })

    if (isNeedVipApprove) { return }

    let approve: any | null = await this.fetchApproveWithTaskAllot(allotExecutorParams, true)
    if (!approve) return

    let isNeedApprove = approve.isNeedApprove === true
    // 有审批
    if (isNeedApprove) {
      this.pending = false
      // @ts-ignore
      approve.data ? approve.data.reason = reAllotParams.reason : null
      // @ts-ignore
      return this.showApproveDialog(approve.data, reAllotParams.customReason || '')
    }
    // 提交
    this.fetchReAllotSubmit(reAllotParams)
  }
  /** 
   * @description 转派提交到负责人
  */
  public async submitReAllotWithExecutor() {
    // 验证负责人是否存在
    let executor = this.executorUser?.userId
    if (!executor) {
      this.pending = false
      Platform.notification({
        title: TASK_NO_EXECUTOR_MESSAGE,
        type: 'error',
      });
      return
    }
    // 验证负责人是否相同
    if (executor === this.task?.executor.userId) {
      this.pending = false
      Platform.notification({
        title: TASK_REALLOT_NOT_SAME_USER_MESSAGE,
        type: 'error',
      });
      return
    }

    // 使用日历派单时开始和结束时间校验
    if (this.allotTypeMode === TaskAllotTypeModeEnum.Calendar) {
      if (!this.calendarStartTime || !this.calendarEndTime) {
        this.pending = false
        let tips = !this.calendarStartTime ? TASK_NO_CALENDAR_START_TIME : TASK_NO_CALENDAR_END_TIME
        return Platform.alert(tips)
      }
      if (this.calendarStartTime !== this.planStartTime || this.calendarEndTime !== this.planEndTime) {
        let timeValidateTip = this.timeValidate()
        if (timeValidateTip) return Platform.alert(timeValidateTip)
      }
    }

    // 验证审批
    const allotExecutorParams = this.buildAllotExcutorParams()

    const reAllotParams = this.buildReAllotParams()
    // 先判断是否需要高级审批
    let isNeedVipApprove = false
    let approveParams = {
      taskId: this.task?.id || '',
      action: this.isReAllot ? 'reAllot' : 'allot',
      allotInfo: reAllotParams,
    }
    await checkNeedVipApprove(approveParams).then((res: any) => {
      if (res?.success) {
        isNeedVipApprove = res?.result?.needVipApprove ?? false
        this.pending = false
        if (isNeedVipApprove) {
          return this.showApproveDialog(res?.result)
        }
      }
    })
    if (isNeedVipApprove) { return }

    let approve: any | null = await this.fetchApproveWithTaskAllot(allotExecutorParams, true)
    if (!approve) return
    approve.data ? approve.data.reason = reAllotParams.reason : null
    let isNeedApprove = approve.isNeedApprove === true
    // 有审批
    if (isNeedApprove) {
      this.pending = false
      return this.showApproveDialog(approve.data, reAllotParams.customReason || '')
    }

    // 提交
    this.fetchReAllotSubmit(reAllotParams)
  }
  /** 
   * @description 时间校验
  */
  public timeValidate() {
    let timeValidateTip = ''
    let nowTime = safeNewDate().getTime()
    let startTime = safeNewDate(this.calendarStartTime).getTime()
    let endTime = safeNewDate(this.calendarEndTime).getTime()
    if (startTime < nowTime || endTime < nowTime) {
      this.pending = false
      timeValidateTip = startTime < nowTime ? PLAN_START_TIME_NOT_LESS_THEN_NOW_MEESSAGE : PLAN_END_TIME_NOT_LESS_THEN_NOW_MEESSAGE
    }
    if (startTime > endTime) {
      this.pending = false
      timeValidateTip = PLAN_END_TIME_NOT_LESS_THEN_PLAN_START_TIME_MEESSAGE
    }
    return timeValidateTip
  }

  /** 
   * @description 将转派人设置为协同人
  */
  public fetchSynergyUserWithReAllot() {
    try {
      // 转派人使用当前登陆用户
      if(!this.loginUser || !isArray(this.synergyUserList)) return

      if(this.synergyUserList.findIndex((item: LoginUser) => item.userId === this.loginUser?.userId) === -1) {
        this.synergyUserList.push(this.loginUser)
      }

    } catch (error) {
      console.error('fetchSynergyUserWithReAllot -> ', error)
    }
  }

  /** 
   * @description 获取默认派单设置
  */
  public getDefaultDispatch() {
    getDefaultExecutor({taskId: this?.task?.id || ''})
    .then((res: any) => {
      let { success, result } = res
      if (!success) return

      let { allotWay = 'ALLOT', defaultExecutor, defaultExecutorConfig } = result || {}
      let allotWayMap: any = {
        ALLOT: TaskAllotTypeEnum.Person,
        TASK_POOL: TaskAllotTypeEnum.Pool,
        SERVICE_PROVIDER: TaskAllotTypeEnum.ServiceProvider,
        AUTO_DISPATCH: TaskAllotTypeEnum.Auto
      }

      if(!allotWay) return

      // 默认配置为工单池并且上次指派结果是工单池
      if(allotWay === 'TASK_POOL' && this.task?.state == 'taskPool') return
      
      if(allotWay === 'ALLOT' && defaultExecutorConfig === 'LAST_DATA') { // 派单给工单负责人 并使用上一次派单结果
        // this.useLastTaskAllotResult() 用这个方法拿不到event
        this.defaultDispatchUseLastTaskAllotResult()
      } else if(allotWay === 'ALLOT' && defaultExecutor) { // 派单给工单负责人
        this.executorUser = defaultExecutor
      }

      this.allotType = allotWayMap[allotWay]
      this.handlerAllotTypeChange(this.allotType, true)

    }).catch(error => {
      console.warn('TaskAllotModalMethods -> getDefaultDispatch -> error', error)
    }).finally(() => {
      this.pending = false
    })
  }

  public async defaultDispatchUseLastTaskAllotResult() {
    try {
      // 取出存储数据
      const taskAllotResult: TaskAllotResult = await this.getDataToStorage(StorageKeyEnum.TaskAllotResult, {})
      // 存储数据是否为空
      if (isEmpty(taskAllotResult)) {
        return Platform.alert(TASK_ALLOT_NOT_STORAGE_RESULT)
      }
      this.executorUser = taskAllotResult.executorUser || null
      this.synergyUserList = taskAllotResult.synergyUserList || []
    } catch(error) {
      console.error(error)
    }
  }

  /** 
   * @description 派单到负责人提交
  */
  public async submitWithExcutor() {
    try {
      // 验证负责人是否存在
      let excutor = this.executorUser?.userId
      if (!excutor) {
        this.pending = false
        return Platform.alert(TASK_NO_EXECUTOR_MESSAGE)
      }

      // 使用日历派单时验证开始和结束时间是否存在
      if (this.allotTypeMode === TaskAllotTypeModeEnum.Calendar) {
        if (!this.calendarStartTime || !this.calendarEndTime) {
          this.pending = false
          let tips = !this.calendarStartTime ? TASK_NO_CALENDAR_START_TIME : TASK_NO_CALENDAR_END_TIME
          return Platform.alert(tips)
        }
        if (this.calendarStartTime !== this.planStartTime || this.calendarEndTime !== this.planEndTime) {
          let timeValidateTip = this.timeValidate()
          if (timeValidateTip) return Platform.alert(timeValidateTip)
        }
      }

      // 验证审批
      const allotExcutorParams = this.buildAllotExcutorParams()

      // 先判断是否需要高级审批
      let isNeedVipApprove = false
      let approveParams = {
        taskId: this.task?.id || '',
        action: this.isReAllot ? 'reAllot' : 'allot',
        allotInfo: allotExcutorParams,
      }
      await checkNeedVipApprove(approveParams).then((res: any) => {
        if (res?.success) {
          isNeedVipApprove = res?.result?.needVipApprove ?? false
          this.pending = false
          if (isNeedVipApprove) {
            return this.showApproveDialog(res?.result)
          }
        }
      })
      if (isNeedVipApprove) { return }

      let approve: any | null = await this.fetchApproveWithTaskAllot(allotExcutorParams)
      if (!approve) return

      let isNeedApprove = approve.isNeedApprove === true
      // 有审批
      if (isNeedApprove) {
        this.pending = false
        this.task.taskNo = approve.data?.taskNo
        return this.showApproveDialog(approve.data)
      }
      // 派单到负责人提交
      this.fetchExcutorSubmit(allotExcutorParams, this.allotTypeMode)

    } catch (error) {
      this.pending = false
      console.warn('TaskAllotModalMethods -> submitWithExcutor -> error', error)
    }
  }

  /**
   * @description 校验是否需要高级审批
   */

  public async checkTaskVipApprove(allotInfo: any) {
    try {
      let approveVipParams = {
        taskId: this.task?.id || '',
        action: this.isReAllot ? 'reAllot' : 'allot',
        allotInfo,
      }

      const { result, success, message } = await checkNeedVipApprove(approveVipParams);

      if (!success) {
        let confirm = await Platform.alert(message)
        if (confirm) window.location.reload()
        return false
      }

      return result;

    } catch (e) {
      console.error(e)
      this.pending = false;
      return null;
    }
  }
  /** 
   * @description 派单到工单池提交
  */
  public async submitWithTaskPool() {
    try {
      // 构建参数
      const allotTaskPoolParams = this.buildAllotTaskPoolParams()

      allotTaskPoolParams.executorId = 'task_pool'

      /* 转派工单池加上转派原因和转派说明参数*/
      if(this.isReAllot) {
        allotTaskPoolParams.reason = this.reason
        allotTaskPoolParams.customReason = this.customReason
      }
      /* 验证高级审批 Start*/
      const result = await this.checkTaskVipApprove(allotTaskPoolParams);
      if (!result) return
      if(result?.needVipApprove){
        this.pending = false
        return this.showApproveDialog(result)
      }
      /* 验证高级审批 End*/

      // 验证审批
      let approve: { isNeedApprove: boolean, data: TaskApprove } | null = await this.fetchTaskAllotTaskPoolApprove(allotTaskPoolParams)
      if (!approve) return

      let isNeedApprove = approve.isNeedApprove === true
      // 有审批
      if (isNeedApprove) {
        this.pending = false
        return this.showApproveDialog(approve.data)
      }

      // 派单到工单池提交
      this.fetchTaskPoolSubmit(allotTaskPoolParams)

    } catch (error) {
      this.pending = false
      console.warn('TaskAllotModalMethods -> submitWithTaskPool -> error', error)
    }
  }

  /** 
   * @description 自动派单提交
  */
  public async submitWithAutoDispatch() {
    try {
      // 验证
      if (!this.matchRule) {
        this.pending = false
        return Platform.alert(TASK_NOT_AUTO_DISPATCH_RULE)
      }

      const autoDispatchParams = this.buildAutoDispatchParams()
      /* 验证高级审批 Start*/
      const result = await this.checkTaskVipApprove(autoDispatchParams);
      if (!result) return
      if(result?.needVipApprove){
        this.pending = false
        return this.showApproveDialog(result)
      }
      /* 验证高级审批 End*/

      const autoDispatchApproveParams: AutoDispatchApproveParams = this.buildAutoDispatchApproveParams()

      let approve = await this.fetchApproveWithAutoDispatch(autoDispatchApproveParams) || null
      if (!approve) return

      const { isNeedApprove, data } = approve
      // 有审批
      if (isNeedApprove) {
        this.pending = false
        return this.showApproveDialog(data)
      }

      // 自动派单提交
      this.fetchAutoDispatchSubmit(autoDispatchParams)

    } catch (error) {
      this.pending = false
      console.warn('TaskAllotModalMethods -> submitWithAutoDispatch -> error', error)
    }
  }

  /** 
   * @description 切换负责人组件状态
  */
  public toggleTaskAllotExecutorComponentPending(pending: boolean = false) {
    this.TaskAllotExcutorComponent?.outsideSetPending(pending)
  }

  /** 
   * @description 转派给自己
  */
  public allotToMyself(event: MouseEvent) {
    // @ts-ignore 取消按钮的焦点
    event?.target?.parentNode?.blur()
    this.handlerAllotTypeChange(TaskAllotTypeEnum.Person)
    this.executorUser = this.loginUser as LoginUser
    this.showClearTaskAllotResultButton = false
    this.submit()
  }

  /** 
   * @description 使用上次派单结果
  */
  public async useLastTaskAllotResult(event: MouseEvent): Promise<void | boolean> {
    // @ts-ignore
    this.$track.clickStat(this.$track.formatParams('LAST_TASK_ALLOT_RESULT'));
    // @ts-ignore 取消按钮的焦点
    event?.target?.parentNode?.blur()
    // 取出存储数据
    const taskAllotResult: TaskAllotResult = await this.getDataToStorage(StorageKeyEnum.TaskAllotResult, {})
    // 存储数据是否为空
    if (isEmpty(taskAllotResult)) {
      return Platform.alert(TASK_ALLOT_NOT_STORAGE_RESULT)
    }

    // 还原上次派单结果
    let allotType = null
    // 显示工单池且上次派单结果为工单池
    if (this.isShowTaskPoolType && taskAllotResult.allotType === TaskAllotTypeEnum.Pool) {
      allotType = taskAllotResult.allotType
    }
    // 显示自动派单且上次派单结果为自动派单
    else if (this.isShowAutoDispatchType && taskAllotResult.allotType === TaskAllotTypeEnum.Auto) {
      allotType = taskAllotResult.allotType
    }
    // 其他为 派单给负责人
    else {
      allotType = TaskAllotTypeEnum.Person
    }

    this.handlerAllotTypeChange(allotType)
    this.executorUser = taskAllotResult.executorUser || null
    this.synergyUserList = taskAllotResult.synergyUserList || []
    // 显示清空派单结果按钮
    this.showClearTaskAllotResultButton = true
  }

  public async getSetCalendar() {
    try {
      let calendarStatus = await getSettingCalendar();
      this.isCalendar = calendarStatus.data.status == 2;
      if (this.isCalendar) {
        this.calendarStartTime = this.planStartTime
        this.calendarEndTime = this.planEndTime
      }
    } catch (error) {
      console.error('fetch PlanTaskEditForm.js getSettingCalendar => error', error);
    }
  }
  /** 
  * @description 获取是否有工单编辑权限
 */
  public async getUserTaskCalendarDispatch() {
    try {
      let taskId = this?.task?.id
      let result = await getTaskCalendarDispatch({ taskId });
      this.isShowCalendarBtn = result.data.checkTaskCalendar
      if (this.isShowCalendarBtn) {
        this.allowEditTask = result.data.checkUpdate
      }
    } catch (error) {
      console.error('fetch PlanTaskEditForm.js getTaskCalendarDispatch => error', error);
    }
  }
}

export default TaskAllotModalMethods
